import 'package:carousel_slider/carousel_slider.dart';
import 'package:eh_mobile/common/routers/index.dart';
import 'package:eh_mobile/common/store/index.dart';
import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/common/values/svg_image.dart';
import 'package:eh_mobile/pages/index.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/center_card.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/device_catgory.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/home_chose_place_view.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/home_dynamic_view.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/home_pageview_bottom.dart';
import 'package:eh_mobile/pages/main/homepage/widgets/home_short_cut_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:get/get_utils/src/platform/platform_io.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import '../../../common/routers/route_pages.dart';
import '../../setup/setup/set_up_manage_page.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'model/home_device_model.dart';

class HomepagePage extends StatefulWidget {
  const HomepagePage({Key? key}) : super(key: key);

  @override
  State<HomepagePage> createState() => _HomepagePageState();
}

class _HomepagePageState extends State<HomepagePage>
    with SingleTickerProviderStateMixin, RouteAware {
  HomepageController controller = Get.put(HomepageController());
 late AnimationController animationController;
 late Animation<double> _animation;

  // 主视图
  Widget _buildView(BuildContext context) {
    return Stack(
      children: [
        Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              GetBuilder(
                  id: controller.chosePlaceViewId,
                  builder: (HomepageController homeController) {
                    return Container(
                        padding: EdgeInsets.only(left: 12.r),
                        height: 30.h,
                        child:
                            Text(homeController.chosePlaceStr, style: 25.ts));
                  }),
              // 顶部设备动态列表
              GetBuilder(
                  id: controller.homeDynamicId,
                  builder: (HomepageController homePageController) {
                    return HomeDynamicView(
                      pageController: controller,
                    );
                  }),
              Container(
                  padding: const EdgeInsets.only(left: 12).w,
                  height: 21.h,
                  child: Text('快捷面板', style: 16.ts)),
              // 快捷面板列表
              Container(
                padding: const EdgeInsets.only(left: 12, right: 12, top: 12).r,
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: HomeShortCutView(
                    controller: controller,
                  ),
                ),
              ),
              // 中间控制区域
              Container(
                width: 1.sw,
                height: 1.sw,
                alignment: Alignment.center,
                child: Stack(
                  alignment: AlignmentDirectional.center,
                  children: [
                    1.sw.sizedBoxWidth,
                    Obx(() => RepaintBoundary(
                          child: AnimatedScale(
                            scale: controller.state.cardTouchDown ? 1.015 : 1,
                            duration: const Duration(milliseconds: 500),
                            child: Container(
                              height: 1.sw - 24.r,
                              width: 1.sw - 24.r,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(25),
                                  color: const Color.fromRGBO(0, 0, 0, 0.38)),
                            ),
                          ),
                        )),

                    RepaintBoundary(
                      child: Container(
                        height: 1.sw - 24.w,
                        width: 1.sw - 24.r,
                        clipBehavior: Clip.antiAlias,
                        decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(const Radius.circular(22.0).r),
                        ),
                        child: _buildCenterControlCardItem(),
                      ),
                    ),
                    //中间卡片区域分页指示器
                    Obx(() => AnimatedPositioned(
                        right: controller.state.cardTouchDown ? 3.r : 6.r,
                        // padding: EdgeInsets.only(
                        //     left: 1.sw -
                        //         (controller.state.cardTouchDown ? 9.r : 13.r)),
                        duration: const Duration(milliseconds: 500),
                        curve: Curves.fastOutSlowIn,
                        child: Obx(() => AnimatedOpacity(
                              opacity: controller.state.cardTouchDown ? 1 : 0,
                              curve: Curves.fastOutSlowIn,
                              duration: Duration(
                                  milliseconds: (controller.state.cardTouchDown
                                      ? 400
                                      : 600)),
                              child: AnimatedSmoothIndicator(
                                activeIndex:
                                    controller.state.centerCurrectPage.value,
                                count: 3,
                                axisDirection: Axis.vertical,
                                effect: WormEffect(
                                    type: WormType.normal,
                                    spacing: 8.0.r,
                                    radius: 2.0.r,
                                    dotWidth: 4.0.r,
                                    dotHeight: 4.0.r,
                                    paintStyle: PaintingStyle.fill,
                                    dotColor: const Color.fromRGBO(
                                        255, 255, 255, 0.2),
                                    activeDotColor: Colors.white),
                              ),
                            )))),
                  ],
                ),
              ),
              // 底部控制区域
              Padding(
                padding: const EdgeInsets.only(left: 12, right: 12).r,
                child: Stack(
                  children: [
                    Container(
                      height: 145.h,
                      width: 1.sw - 24.r,
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(0, 0, 0, 0.38),
                          borderRadius: BorderRadius.circular(25)),
                    ),
                    SizedBox(
                      height: 145.h,
                      width: 1.sw - 24.r,
                      child: GetBuilder(
                          id: controller.deviceCategoryWidgetId,
                          builder: (HomepageController pageController) {
                            return pageController.pageList.isNotEmpty
                                ? PageView.builder(
                                    physics: const BouncingScrollPhysics(),
                                    controller:
                                        controller.deviceCategoryPageController,
                                    scrollDirection: Axis.horizontal,
                                    itemCount: controller.pageList.length,
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      return RepaintBoundary(
                                        child: DeviceCategoryView(index),
                                      );
                                    })
                                : Container();
                          }),
                    ),
                  ],
                ),
              ),
              GetBuilder(
                  id: controller.smoothPageViewId,
                  builder: (HomepageController pageController) {
                    return HomePageViewBottom(
                      pageController: controller,
                    );
                  }),
            ]),
        Positioned(
          left: -60.w,
          top: -30.h,
          width: 380.w,
          height: 232.h,
          child: GetBuilder(
              id: controller.cardPlaceViewId,
              builder: (HomepageController homeController) {
                return Visibility(
                    visible: homeController.isShowCardView,
                    child: const HomeChosePlaceView());
              }),
        ),
        Positioned(
          left: 0,
          top: 0,
          child: Container(
            color: Colors.transparent,
            width: 135.w,
            height: ScreenUtil().statusBarHeight,
          ).onClick(() {
            if (controller.deviceSystemList.length < 2) {
              return;
            }
            controller.isShowCardView = !controller.isShowCardView;
            controller.update([controller.cardPlaceViewId]);
          }),
        ),
      ],
    );
  }

// 创建导航按钮
  Widget _buildNavigationButton(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        IconButton(
          icon: SvgPicture.asset(
            SVGImage.icHomeSvg,
            theme: const SvgTheme(
                currentColor: Color.fromARGB(255, 51, 51, 51), fontSize: 32),
          ),
          onPressed: () {
            Get.to(MessagePage());
          },
          alignment: Alignment.bottomLeft,
        ),
        10.sizedBoxWidth,
        IconButton(
          icon: SvgPicture.asset(
            SVGImage.icOptionSvg,
            theme:
                const SvgTheme(currentColor: Color(0xffEBEBEB), fontSize: 32),
          ),
          onPressed: () {
            animationController.forward();
            showCupertinoModalBottomSheet(
                topRadius: Radius.circular(24.r),
                enableDrag: false,
                context: context,
                builder: (context) => SetupManagePage(
                      callBack: () {
                        animationController.reverse();
                      },
                    ));
          },
          alignment: Alignment.bottomLeft,
        ),
      ],
    );
  }

  // 构建中间控制区域item
  Widget _buildCenterControlCardItem() {
    return Listener(
      onPointerDown: (event) {
        // print('手指按下');
        controller.centerCardTouchDown();
      },
      onPointerUp: (event) {
        // print('手指抬起');
        controller.centerCardTouchUp();
      },
      child: Container(
        alignment: Alignment.center,
        height: 1.sw - 24.w,
        width: 1.sw - 24,
        child: CarouselSlider(
          carouselController: controller.centerCardPageController,
          options: CarouselOptions(
            scrollPhysics: const BouncingScrollPhysics(),
            clipBehavior: Clip.none,
            onPageChanged: (index, reason) {
              controller.state.centerCurrectPage.value = index;
            },
            viewportFraction: 1,
            enlargeFactor: 0.35,
            aspectRatio: 1,
            enlargeCenterPage: true,
            scrollDirection: Axis.vertical,
            autoPlay: false,
          ),
          items: [
            CenterCardWidget(),
            CenterCardWidget(),
            CenterCardWidget(),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    double screenRatio = 1.sw / 1.sh;
    return ScaleTransition(
      scale: _animation,
      child: Container(
        decoration: BoxDecoration(
            borderRadius: _animation != null
                ? BorderRadius.only(
                    topLeft: Radius.circular(24.r),
                    topRight: Radius.circular(24.r))
                : BorderRadius.circular(0),
            image: const DecorationImage(
                image: ExactAssetImage('assets/images/main_bg.png'),
                fit: BoxFit.cover)),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            iconTheme: const IconThemeData(color: Colors.white, size: 28),
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarIconBrightness: (GeneralPlatform.isAndroid
                  ? Brightness.light
                  : Brightness.dark),
              statusBarBrightness: (GeneralPlatform.isAndroid
                  ? Brightness.light
                  : Brightness.dark),
              // statusBarColor: Colors.white,
            ),
            toolbarHeight: 0,
          ),
          // 如果屏幕宽高比高于18:9,代表为全面屏不使用滑动
          body: Column(
            children: [
              Container(
                padding: EdgeInsets.only(right: 12.w),
                child: _buildNavigationButton(context),
              ),
              (screenRatio <= 0.5)
                  ? _buildView(context)
                  : Expanded(
                      child: SingleChildScrollView(
                        padding: EdgeInsets.only(bottom: 10.h),
                        child: _buildView(context),
                      ),
                    ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    controller.initData();
    animationController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 600));
    //非线性动画
    _animation = Tween<double>(begin: 1.0, end: 0.89).animate(
      CurvedAnimation(
        parent: animationController,
        curve: Curves.easeIn,
      ),
    );

    if (controller.deviceCategoryList.isEmpty) {
      List mapList =
          UserStore().userStoreCache.read('deviceCategoryList') ?? [];
      if (mapList.isNotEmpty) {
        for (var element in mapList) {
          HomeDeviceModelData deviceModelData;
          if (element is Map) {
            deviceModelData = HomeDeviceModelData.fromJson(element);
          } else {
            deviceModelData = element;
          }
          controller.deviceCategoryList.add(deviceModelData);
        }
        controller.update(
            [controller.deviceCategoryWidgetId, controller.smoothPageViewId]);
      }
    }
  }

  @override
  void dispose() {
    RouterPages.observer.unsubscribe(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouterPages.observer.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void didPopNext() {
    super.didPopNext();
    animationController.reverse();
  }
}
